const randomNum = (min=0, max=10000) => {
  return parseInt(Math.random()*(max - min) + min+'');
}
const randomString = (length, chats?)=> {
  if (!length) length = 1
  if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
  let str = ''
  for (let i = 0; i < length; i++) {
    const num = randomNum(0, chats.length - 1)
    str += chats[num]
  }
  return str
}
export const createRes = function (msg:any,data?:any) {
  let status = msg === true;
  return {
   status: status?200:201,//不可更改字段
   message: status?'':msg,//不可更改字段
   result: data,//不可更改字段
   code: status?200:201,
   success: status
  }
};
export const DataTypes = {
  String: '[object String]',
  Array: '[object Array]',
  Object: '[object Object]',
  Number: '[object Number]',
};
export const isNone = data=>{
  return data === ''||data === undefined||data === null;
}
export const isObject = data => Object.prototype.toString.call(data) === "[object Object]";
export const isArray = data => Object.prototype.toString.call(data) === "[object Array]";
export const isNumber = data => Object.prototype.toString.call(data) === "[object Number]";
export const isString = data => Object.prototype.toString.call(data) === "[object String]";

export const checkData = function (_data,template) {
  let data = JSON.parse(JSON.stringify(_data)),
      echoData;
  let list;
  if(!isObject(template)){
    return createRes('请选择模板');
  }
  if(isObject(_data)){
    list = [data];
    echoData = [{}];
  }else if(isArray(_data)){
    list = data;
    echoData = data.map(item=>{return {}});
  }else{
   return createRes('数据只能为数组或对象');
  }
  let nowTime = Date.now();
  for(let i = 0; i < list.length;i++){
    let item = list[i];
    for(let key in template){
      let {type,defaultValue,automatic,required,memory} = template[key];
      if(automatic && isNone(item[key]) && type === 'String'){
        item[key] = 'indexDB_'+key+'_'+randomString(8)+'_'+nowTime;
      }
      if(required && isNone(item[key])){
        return createRes(`${key}不能为空`);
      }
      item[key] = (item[key]===''||item[key] === undefined)?defaultValue:item[key];
      if(type != 'Any' && DataTypes[type] != Object.prototype.toString.call(item[key])){
        return createRes(`${key}类型为${type}`);
      }
      echoData[i][key] = item[key];
    }
  }
  return createRes(true,echoData);
}
export const makePage = function({pageNo=1,pageSize=10,list=[]}){
	let echo = {total:list.length,records:[],pages:~~(list.length/pageSize)+1,current:pageNo};
	if((pageNo-1)*pageSize >= echo.total){
		return echo;
	}
	echo.records = list.splice((pageNo-1)*pageSize,pageSize);
	return echo;
}